/*
 * Copyright 2011 Mark Davidson.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.dctmcommons.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dctmcommons.DctmCommonsException;
import org.dctmcommons.IAttribHelper;
import org.dctmcommons.ITypedObjectTransformer;

import com.documentum.fc.client.IDfTypedObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfLogger;

/**
 * Callback class used to transform a collection of {@link IDfTypedObject}
 * objects to a {@link List} of {@link Map} objects.
 */
public class MapBasedTypedObjectTransformer implements
		ITypedObjectTransformer {

	/** The attribute helper. */
	private final IAttribHelper attribHelper = AttribHelper.getInstance();
	
	/** The attribute names. */
	private String[] attribNames = null;
	
	/** The results. */
	private final List<Map<String, Object>> results =
									new ArrayList<Map<String,Object>>();

	/** Default constructor. */
	private MapBasedTypedObjectTransformer() {}
	
	/**
	 * Factory method.
	 * @return A {@link MapBasedTypedObjectTransformer} instance
	 */
	public static MapBasedTypedObjectTransformer getInstance() {
		return new MapBasedTypedObjectTransformer();
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.dctmcommons.ITypedObjectCallback#read(com.documentum.fc.client.IDfTypedObject)
	 */
	@Override
	public boolean read(final IDfTypedObject typedObject)
		throws DfException {
		try {
			attribNames = attribHelper.getAttribNames(typedObject);
			results.add(attribHelper.readAttribs(typedObject, attribNames));
		} catch (DfException e) {
			DfLogger.error(this, e.getMessage(), null, e);
			throw new DctmCommonsException(e.getMessage(), e);
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * @see org.dctmcommons.ITypedObjectTransformer#getResults()
	 */
	@Override
	public List<Map<String, Object>> getResults() {
		return (results.size() == 0) ? null : results;
	}
}
